'use strict';
let fs = require("fs");
let path = require("path");
let router = require("koa-router")();

function filterFile() {
    let file = fs.readdirSync(__dirname);
    let js_file = file.filter(f => {
        return f.endsWith('.js') && f !== 'index.js'
    })
    return js_file;
}

function register(files) {
    files.forEach(element => {
        let fullPath = path.join(__dirname, element);
        let routerFile = require(fullPath);

        for (let x in routerFile) {
            //获取数组的值
            let valueArr = routerFile[x];
            //获取数组类型
            let type = valueArr[0];
            // console.log(x);
            // console.log(valueArr);
            if (type === "post") {
                if (valueArr.length === 2) {
                    let fn = valueArr[1];
                    router.post(x, fn);
                } else {
                    let auth = valueArr[1];
                    let fn = valueArr[2];
                    router.post(x, auth, fn);
                }
            } else if (type === "get") {
                if (valueArr.length === 2) {
                    let fn = valueArr[1];
                    router.get(x, fn);
                } else {
                    let auth = valueArr[1];
                    let fn = valueArr[2];
                    router.get(x, auth, fn);
                }
            } if (type === "delete") {
                if (valueArr.length === 2) {
                    let fn = valueArr[1];
                    router.delete(x, fn);
                } else {
                    let auth = valueArr[1];
                    let fn = valueArr[2];
                    router.delete(x, auth, fn);
                }
            } if (type === "put") {
                if (valueArr.length === 2) {
                    let fn = valueArr[1];
                    router.put(x, fn);
                } else {
                    let auth = valueArr[1];
                    let fn = valueArr[2];
                    router.put(x, auth, fn);
                }
            }
        }

    });
}

module.exports = function () {
    let controller = filterFile();
    register(controller);
    return router.routes();
}